import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/ui/src/html.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';

class HomePopupView extends StatefulWidget {
  const HomePopupView({super.key, this.list = const [], this.option});
  //数据列表
  final List<dynamic> list;
  //比例
  final HomePopupOption? option;

  @override
  State<HomePopupView> createState() => _HomePopupViewState();
}

class _HomePopupViewState extends State<HomePopupView> {
  ValueNotifier<bool> showCloseButton = ValueNotifier<bool>(true);
  HomePopupOption option = HomePopupOption();
  @override
  void initState() {
    if (widget.option != null) {
      option = widget.option as HomePopupOption;
    }
    if (option.alwayShowCloseButton != true && widget.list.length > 1) {
      showCloseButton.value = false;
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: option.aspectRatio ?? 4 / 5,
      child: Container(
        clipBehavior: Clip.hardEdge,
        margin: const EdgeInsets.all(UiTheme.spacingX),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: const [
            BoxShadow(
              color: Colors.black54,
              blurRadius: 10,
              spreadRadius: 2,
            )
          ],
          borderRadius: BorderRadius.circular(UiTheme.boxRadiusX),
        ),
        child: Stack(
          children: [
            Positioned.fill(
              child: widget.list.length > 1
                  ? Swiper.list(
                      onIndexChanged: (index) {
                        if (index == widget.list.length - 1) {
                          showCloseButton.value = true;
                        }
                      },
                      list: widget.list,
                      builder: (context, data, index) {
                        return itemView(context, data);
                      },
                      autoplay: option.autoplay == true,
                      autoplayDelay: 5000,
                      pagination: SwiperCustomPagination(
                        builder: (context, config) {
                          return Align(
                            alignment: Alignment.bottomCenter,
                            child: Padding(
                              padding: const EdgeInsets.only(bottom: 8.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  for (var i = 0; i < config.itemCount; i++)
                                    Container(
                                      height: 8,
                                      width: 8,
                                      margin: const EdgeInsets.symmetric(
                                          horizontal: 2),
                                      decoration: BoxDecoration(
                                          color: config.activeIndex == i
                                              ? UiTheme.primary
                                              : Colors.grey,
                                          borderRadius:
                                              BorderRadius.circular(5),
                                          boxShadow: const [
                                            BoxShadow(
                                              color: Colors.black12,
                                              blurRadius: 10,
                                            ),
                                          ]),
                                    )
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    )
                  : itemView(
                      context,
                      widget.list.first,
                    ),
            ),
            ValueListenableBuilder(
              valueListenable: showCloseButton,
              builder: (context, state, child) {
                Widget button;

                if (option.closeStyle == 'icon') {
                  button = Positioned(
                    top: 2,
                    right: 2,
                    child: IconButton(
                      onPressed: () {
                        App.back(context);
                      },
                      icon: const CircleAvatar(
                        radius: 12,
                        backgroundColor: Colors.white70,
                        child: Icon(
                          Icons.close,
                          size: 18,
                        ),
                      ),
                    ),
                  );
                } else {
                  button = Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: UiTheme.spacingX,
                        vertical: 20,
                      ),
                      width: double.infinity,
                      child: UiButton(
                        onPressed: () {
                          App.back(context);
                          if (Ui.isNotEmpty(option.buttonUrl)) {
                            App.push(option.buttonUrl.toString());
                          }
                        },
                        child: Text(option.buttonText ?? '知道了'),
                      ),
                    ),
                  );
                }

                return state ? button : Container();
              },
            ),
          ],
        ),
      ),
    );
  }

  UiTap itemView(BuildContext context, data) {
    return UiTap(
      onTap: () {
        if (option.closeAfterClickItem == true) {
          App.back(context);
        }
        App.push(data['url'] ?? '', openType: data['openType'] ?? '');
      },
      child: data['type'] == 'text'
          ? Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(
                    left: 15,
                    right: 15,
                    top: 15,
                  ),
                  child: Text(
                    data['title'],
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(
                      bottom: 30,
                      top: 10,
                      left: 15,
                      right: 15,
                    ),
                    child: SingleChildScrollView(
                      child: UiHtml(
                        data: data['content'],
                        dense: true,
                      ),
                    ),
                  ),
                ),
              ],
            )
          : ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: CachedNetworkImage(
                imageUrl: data['image'],
                fit: BoxFit.cover,
              ),
            ),
    );
  }
}

class HomePopupOption {
  bool? alwayShowCloseButton;
  bool? closeAfterClickItem;
  bool? autoplay;
  double? aspectRatio;
  String? closeStyle;
  String? buttonUrl;
  String? buttonText;

  HomePopupOption({
    this.alwayShowCloseButton = false,
    this.closeAfterClickItem = false,
    this.autoplay = false,
    this.aspectRatio = 4 / 5,
    this.closeStyle = 'icon',
    this.buttonUrl = '',
    this.buttonText = '知道了',
  });

  HomePopupOption.fromJson(Map<String, dynamic> json) {
    alwayShowCloseButton = json['alwayShowCloseButton'] ?? false;
    closeAfterClickItem = json['closeAfterClickItem'] ?? false;
    aspectRatio = json['aspectRatio'] ?? 4 / 5;
    closeStyle = json['closeStyle'] ?? 'icon';
    buttonUrl = json['buttonUrl'] ?? '';
    buttonText = json['buttonText'] ?? '知道了';
    autoplay = json['autoplay'] ?? false;
  }
}
